import Vue from "vue";
import Vuex from "vuex";
// import { delete } from "_vue@2.6.12@vue/types/umd";
// import axios from 'axios'
import appApi from '../../utils/api'
// import router from '../router'
Vue.use(Vuex);
export default {
    namespaced: true,
    state: {
        books: {
            loading_over: false,
            rscontype: false,
            Namedparent: {
                key: '1',
                name: 'Paperbook'
            },
            detailquery: {
                searchtitle: '',
                id: ''
            },
            showdetail: false,
            bookinfo_already_show: false,
            show_sider: false,
            show_pagination: false,
            fieldsAllow: {
                sortFields: [
                    { id: "relevance", name: "相关度排序" },
                    { id: "title", name: "书名" },
                    { id: "author", name: "作者" },
                    { id: "publisher", name: "出版社" },
                    { id: "pubYear", name: "出版日期" },
                    { id: "callNo", name: "索书号" },
                ],
                searchAdvCode: { title: "", author: "03", publisher: "09", isbn: "05" },
                searchKeys: [
                    { "id": "", name: "任意词" },
                    { "id": "02", name: "书名" },
                    { "id": "03", name: "责任者" },
                    { "id": "04", name: "主题词" },
                    { "id": "05", name: "ISBN" },
                    { "id": "09", name: "出版社" },
                    { "id": "10", name: "丛书名" },
                    { "id": "07", name: "分类号" },
                    { "id": "08", name: "索书号" },
                ],
                sortTypes: ["desc", "asc"],
                defaultPageSize: 20,
            },
            // 选择标签
            tags: [],
            // qs: 请求参数
            qs: {
                searchWords: [{
                    fieldList: [
                        { fieldCode: "", fieldValue: "" },
                        // { "fieldCode": "", "fieldValue": "红楼梦", "fieldConj": "AND" },
                        // { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                    ],
                }],
                filters: [

                ],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                pageCount: 1,
                locale: "zh_CN",
                first: true
            },
            isbn_: [], //isbn
            // rs:检索结果
            rs: {
                total: 180,
                content: [
                    // {
                    //     "author": "(美) 鲁道夫·焦梅蒂著",
                    //     "callNo": "TP316.85/58",
                    //     "docTypeName": "中文图书",
                    //     "isbn": "978-7-111-59829-9",
                    //     "marcRecNo": "39697054624f516a5a3347416b53596b5a4e677741673d3d",
                    //     "num": 1,
                    //     "pubYear": "2018",
                    //     "publisher": "机械工业出版社",
                    //     "title": "GNU/Linux嵌入式快速编程"
                    // },
                    // {
                    //     "author": "杨明华, 谭励, 于重重等编著",
                    //     "callNo": "TP368.5/42",
                    //     "docTypeName": "中文图书",
                    //     "isbn": "978-7-121-06844-7, 978-7-89485-838-2",
                    //     "marcRecNo": "6d372b4458656d77675833676542487a5848492f50513d3d",
                    //     "num": 2,
                    //     "pubYear": "2008",
                    //     "publisher": "电子工业出版社",
                    //     "title": "LAMP网站开发黄金组合Linux+Apache+MySQL+PHP"
                    // },
                ],
                facetsList: [{
                        "facetList": [{
                                "code": "CHI",
                                "count": 13,
                                "name": "中文"
                            },
                            {
                                "code": "ENG",
                                "count": 1,
                                "name": "英语"
                            }
                        ],
                        "id": "langFacet",
                        "label": "语言"
                    },
                    {
                        "facetList": [{
                                "code": "2020",
                                "count": 1,
                                "name": "2020"
                            },
                            {
                                "code": "2018",
                                "count": 1,
                                "name": "2018"
                            },
                        ],
                        "id": "pubYearFacet",
                        "label": "出版年份"
                    }
                ],

                "filters": [
                    // { "fieldName": "subjectFacet", "values": ["红楼梦", "文学研究"] },
                    // { "fieldName": "locationFacet", "values": ["03005"] }
                ],
                "limiter": [],
                "sortField": "relevance",
                "sortType": "desc",
                "pageSize": 20,
                "pageCount": 1,
                "locale": "zh_CN",
                "first": true,
            },

        },
    },
    mutations: {
        // 判断详情是否打开
        SHOW_DETAIL(state, status) {
            state.books.showdetail = status;
        },
        // 获取详情参数
        ChangeDetailQuery(state, status) {
            state.books.detailquery.searchtitle = status.searchtitle;
            state.books.detailquery.id = status.id;
        },
        // 侧边栏是否打开
        BOOKINFO_ALREADY_SHOW(state, is_show) {
            state.books.bookinfo_already_show = is_show;
        },
        // 清空搜索参数
        CLEAR_QS(state) {
            var qs = {
                searchWords: [{
                    fieldList: [
                        { fieldCode: "", fieldValue: "" },
                        // { "fieldCode": "", "fieldValue": "红楼梦", "fieldConj": "AND" },
                        // { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                    ],
                }],
                filters: [

                ],
                limiter: [],
                sortField: "relevance",
                sortType: "desc",
                pageSize: 20,
                pageCount: 1,
                locale: "zh_CN",
                first: true
            };
            state.books.qs = qs;
            state.books.rs.filters = [];
        },
        // 获取过滤条件
        UpdateQsFacets(state, facetsList) {
            state.books.qs.filters = facetsList;
        },
        // 获取过滤条件
        UpdateRsFacets(state, facetsList) {
            state.books.rs.facetsList = facetsList;
        },
        // 获取总数
        UpdateRsTotal(state, total) {
            state.books.rs.total = total;
        },
        // 获取搜索结果内容
        UpdateRsContent(state, books) {
            state.books.rs.content = books;
        },
        ///
        /**
         * 更新qs 中的检索词
         * 1、更新keyword
         * 2、这里通通重置为第1页
         * 3、
         * searchWords: [
                    {
                        fieldList: [
                            { fieldCode: "", fieldValue: "红楼梦" },
                            { "fieldCode": "04", "fieldValue": "曹雪芹", "fieldConj": "AND" }
                        ],
                    }
                ],
         * @param {*} state 
         * @param {检索词，是} search_keyword 
         * 
         */
        // 获取搜索关键字  页码
        UpdateQsSearchKeyWord(state, search_keyword) {
            this.commit(state.books.Namedparent.name + "/UpdateQsSearchKeyWordV2", search_keyword, 1);
        },
        // 清空搜索关键字
        clearsearchwordks(state, value) {
            state.books.qs.searchWords[0].fieldList = [
                { fieldCode: "", fieldValue: value },
            ];
        },
        // 获取搜索条件
        UpdateQsSearchKeyWordV2(state, search_keyword, current_page) {
            state.books.qs.searchWords[0].fieldList[0].fieldValue = search_keyword;
            state.books.qs.pageCount = current_page;
            state.books.qs.filters = [];
        },
        //高级检索条件，多个关键词
        UpdateQsSearchFieldListAdv(state, search_field_list) {
            state.books.qs.searchWords[0].fieldList = search_field_list;
        },
        // 年代限制 ["DT:1999/2021"] 这种格式
        UpdateQsLimiter(state, limiter) {
            state.books.qs.limiter = limiter;
        },
        // 获取搜索类型
        ChangeQsSearchField(state, search_field) {
            state.books.qs.searchWords[0].fieldList[0].fieldCode = search_field;
        },
        // 获取搜索类型
        ChangeSortType(state, sortType) {
            state.books.qs.sortType = sortType;
        },
        // 获取排序
        ChangeSortField(state, sortField) {
            state.books.qs.sortField = sortField;
            // state.books.qs. = sortField;
        },
        // 获取搜索页码
        ChangeCurrentPage(state, currentPage) {
            state.books.qs.pageCount = currentPage;
        },
        // 获取页码
        ChangeCurrentPageWithOutSync(state, currentPage) {
            state.books.qs.pageCount = currentPage;
        },
        // 清空搜索内容
        ClearBooksContents(state) {
            state.books.rs.content = [];
        },
        
        PARAMS_INIT_QS(state, rs) {
            state.books.rs = rs;
        },
        // 是否展示侧边栏
        SHOW_SIDER(state, status) {
            state.books.show_sider = status;
        },
        // 是否展示分页
        SHOW_PAGINATION(state, status) {
            state.books.show_pagination = status;
        },
        // 添加书籍列表
        AddBook(state, {
            author,
            category,
            bisbn,
            isbn,
            pub_year,
            publisher,
            title,
            filetype,
            bookid,
            cover
        }) {
            var book = {
                author: author,
                category: category,
                bisbn: bisbn,
                isbn: isbn,
                pub_year: pub_year,
                publisher: publisher,
                title: title,
                filetype: filetype,
                bookid: bookid,
                cover: cover,
            };
            state.books.rs.content.push(book);
        },
        removeFilters(state, index) {
            // 移除弹窗
            state.dialogList.splice(index, 1);
        },
        // 获取搜索筛选
        SearchSideUpdateFilters(state, { fieldName, value, code,lable }, is_search_books) {
            // var filter_len = state.books.qs.filters.length;
            var findFilter = false;
            state.books.qs.filters.forEach(function(item, i) {
                var filter = item;
                if (filter.fieldName == fieldName) {
                    findFilter = true;
                    var index = filter.values.indexOf(code);
                    console.log(index)
                    if (index >= 0) {
                        filter.values.splice(index, 1);
                        filter.name.splice(index, 1);
                        if (state.books.qs.filters[i].values.length == 0) {
                            state.books.qs.filters.splice(i, 1);
                        }
                    } else {
                        filter.values.push(code);
                        filter.name.push(value);
                    }
                }
            });



            // for (let i = 0; i < filter_len; i++) {
            //     var filter = state.books.qs.filters[i];
            //     console.log(filter)
            //     console.log(fieldName)

            //     if (filter.fieldName == fieldName) {
            //         findFilter = true;
            //         console.log('---------------')
            //         var index = filter.values.indexOf(code);
            //         // 如果filter 中已经存在value，则之前为选中状态，现在要删除
            //         // 如果之前未选中，则现在要增加
            //         console.log(i)
            //             //state.books.qs.filters.splice(i, 1);
            //         if (index >= 0) {
            //             console.log(index + '---------')
            //                 // filter.values.splice(index, 1);
            //                 // filter.name.splice(index, 1);
            //                 // console.log(state.books.qs.filters[i].values)
            //                 // if (state.books.qs.filters[i].values.length == 0) {
            //             state.books.qs.filters.splice(i, 1);
            //             // }
            //         } else {
            //             // filter.values.push(code);
            //             // filter.name.push(value);
            //         }

            //         //   Vue.set(state.books.qs.filters, i, filter);
            //     }

            // }
            if (findFilter == false) {
                //// 如果fieldName对应的fieldName如subjectFacet 是第一次添加
                state.books.qs.filters.push({ "fieldName": fieldName, "values": [code], 'name': [value],lable:lable });
            }
            // for (var i = 0; i < filter_len; i++) {
            //     if (state.books.qs.filters[i].values.length == 0) {
            //         state.books.qs.filters.splice(i, 1);
            //     }
            // }
            is_search_books = true;
            if (is_search_books) {
                this.dispatch("Paperbook/GetBooks")
            }
        },
        // 加载loading
        Changeloading(state, status) {
            state.books.loading_over = status;
        }
    },
    actions: {
        // 初始化加载
        GetBooks(context) {
            context.state.books.loading_over = true;
            appApi.PagerList(context.state.books.qs)
                .then(response => {
                    var data = response.data ? response.data.content : [];
                    var x = data;
                    if (response.status == 200) {
                        if (context.state.books.rs.content.length > 0) {
                            context.state.books.rs.content = [];
                        }
                        var book_length = x.length;
                        var books = [];
                        for (var i = 0; i < book_length; i++) {
                            var book = {
                                id: 0,
                                title: "",
                                author: "",
                                publisher: "",
                                publish_date: "",
                                pub_year: 0,
                                cover: "",
                                intro: "",
                                isbn: "",
                                bisbn: "",
                                category: "",
                                cates: "",
                                booktype: "",
                                filetype: "",
                                bookid: "",
                                assertId: "",
                                src: "",
                                view_count: 0,
                                extid: "",
                                ext: "",
                                muluText: "",
                                created_at: 0,
                                updated_at: 0,
                                pc_read: "",
                                pc_epub: "",
                                wx_read: "",
                                wx_epub: "",
                                detail: "",
                                num: '',
                                ebooklist: []
                            };
                            book.author = x[i].author;
                            book.category = x[i].callNo;
                            book.cates = x[i].callNo;
                            book.bisbn = x[i].isbn;
                            book.isbn = x[i].isbn.replace("-", "");
                            book.pub_year = parseInt(x[i].pubYear);
                            book.publish_date = x[i].pubYear;
                            book.publisher = x[i].publisher;

                            book.src = book.publisher;
                            book.title = x[i].title;
                            book.filetype = x[i].docTypeName;
                            book.bookid = x[i].marcRecNo;
                            book.num = x[i].num;
                            var isbn = book.isbn;
                            if (isbn.indexOf(",") > 0) {

                                var isbns = isbn.split(",");
                                if (isbns.length > 1) {
                                    isbn = isbns[0];
                                    isbn = isbn.replace("-", "");
                                }
                            }
                            book.cover =
                                "http://api.bcd.jslib.cn/search?appid=bk7895412578&q=" + isbn;
                            books[i] = book;
                        }
                        for (var ins = 0; ins < books.length; ins++) {
                            var isbn_ = { fieldValue: "" };
                            isbn_.fieldValue = books[ins].isbn.replace(/-/g, "");
                            context.state.books.isbn_.push(isbn_)
                                // await axios.get('http://login.epac.user.kim/frontend/web/index.php?r=ebooks/ajaxcxlocalisbns&isbns=' + books[eb].isbn.replace(/-/g, ""))
                                //     .then(function(res) {
                                //         if (res.status == 200) {
                                //             console.log('555555555555555555555555555555555555555555555555555555555555555----------' + eb + '----------' + items)
                                //             books[items].ebooklist = res.data;

                            //         }
                            //     })
                        }
                        context.dispatch('asyncFunc', { books, ins })
                        context.commit("SHOW_PAGINATION", true);
                        context.commit("SHOW_SIDER", true);
                        // context.state.books.rs.content = books;
                        context.commit("UpdateRsContent", books);
                        context.commit("UpdateRsTotal", parseInt(response.data.total));
                        // context.commit("UpdateQsTotal", response.data.facetsList);
                        context.commit("UpdateRsFacets", response.data.facetsList);
                        context.commit("UpdateQsFacets", response.data.filters);
                        // that.search_result.facets_lists = response.data.facetsList;
                        // state.books.rs.facetsList;


                        // console.log("push words:", x.totalCount, book_length);
                    }
                    context.state.books.loading_over = false;
                    context.state.books.rscontype = true;
                })
                .catch(function(error) {
                    // 请求失败处理
                    console.log("runoob", error);
                });
        },
        // 检索相关书籍
        asyncFunc(context) {
            var isbns_ = context.state.books.isbn_;
            var isbnscon = '';
            for (var i = 1; i < isbns_.length; i++) {
                if (isbns_[i].fieldValue) {
                    isbnscon += isbns_[i].fieldValue + '%20'
                }
            }
            return new Promise((resolve) => {
                setTimeout(() => {
                    appApi.PagerasyncFunc(isbnscon.substr(0, isbnscon.length - 1))
                        .then(res => {
                            if (res.status == 200) {
                                for (var i = 0; i < context.state.books.rs.content.length; i++) {
                                    for (var j = 0; j < res.data.length; j++) {
                                        if (context.state.books.rs.content[i].isbn.replace(/-/g, "") == res.data[j].isbn) {
                                            context.state.books.rs.content[i].ebooklist = res.data[j]
                                        }
                                    }
                                }
                            }
                        })
                    resolve()
                }, 1)
            })
        }
    },
    getters: {
        getQS: state => {
            return state.books.qs;
            // return state.books.filter(todo => todo.done)
        }
    }
}